<?php


namespace app\api\controller\v1;


use app\api\model\User;
use app\api\service\BaseToken;
use app\api\validate\AddressValidate;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use think\Controller;

class Address extends Controller
{
    public function createUpdateAddress()
    {
        $validate = new AddressValidate();
        // 验证
        $validate->goCheck();
        // 获取uid
        $uid = BaseToken::getCurrentUid();
        // 判断是否有该用户
        $user = User::get($uid);
        if (!$user) {
            throw new UserException();
        }
        // 验证客户端上传的全部post变量
        $dataArray = $validate->getDataRules(input('post.'));

        // 关联查询用户地址
        $userAddress = $user->address;
        if (!$userAddress) {
            // 用户没有地址，新增
            $user->address()->save($dataArray);
        } else {
            // 用户有地址，更新（读取关联address，没有（））
            $user->address->save($dataArray);
        }
        return json(new SuccessMessage(), 201);
    }
}